package com.breeze.blockchain.auth;

import static com.breeze.blockchain.auth.util.LoginLogics.isApp;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollUtil;
import com.breeze.blockchain.mybatis.entity.PermissionDo;
import com.breeze.blockchain.mybatis.entity.RolePermissionDo;
import com.breeze.blockchain.service.AdminService;
import com.breeze.blockchain.service.PermissionService;
import com.breeze.blockchain.service.RolePermissionService;
import com.breeze.blockchain.service.RoleService;
import com.breeze.components.core.util.id.IdAssembler;
import jakarta.annotation.Resource;
import java.util.List;
import org.springframework.stereotype.Component;

/**
 * 权限角色注入
 *
 * @author breeze
 */
@Component
public class StpInterfaceImpl implements StpInterface {

  @Resource AdminService adminService;
  @Resource RoleService roleService;
  @Resource PermissionService permissionService;
  @Resource RolePermissionService rolePermissionService;

  @Override
  public List<String> getPermissionList(Object loginId, String loginType) {
    if (isApp(loginType)) {
      return List.of();
    }
    // 该用户所有权限key
    return queryPermissionKey(Long.valueOf(String.valueOf(loginId)));
  }

  @Override
  public List<String> getRoleList(Object loginId, String loginType) {
    if (isApp(loginType)) {
      return List.of();
    }
    // 该用户所有角色
    return queryRoleKeyCache(Long.valueOf(String.valueOf(loginId)));
  }

  public List<String> queryPermissionKey(Long adminId) {
    var admin = adminService.getExistById(adminId);
    var role = roleService.getExistRoleById(admin.getRoleId());
    role.checkRoleStatus();
    // 角色id查权限
    var rolePermissions =
        rolePermissionService
            .queryChain()
            .eq(RolePermissionDo::getRoleId, admin.getRoleId())
            .list();
    if (CollUtil.isEmpty(rolePermissions)) {
      return List.of();
    }
    // 查权限资源
    return permissionService
        .queryChain()
        .in(
            PermissionDo::getId,
            IdAssembler.assembleIdSet(rolePermissions, RolePermissionDo::getPermissionId))
        .list()
        .stream()
        .map(PermissionDo::getKey)
        .toList();
  }

  public List<String> queryRoleKeyCache(Long adminId) {
    var admin = adminService.getExistById(adminId);
    var role = roleService.getExistRoleById(admin.getRoleId());
    role.checkRoleStatus();
    return List.of(role.getRoleKey());
  }
}
